<?php

namespace backend\controllers;

use backend\models\GrpBrand;
use backend\models\GrpClass;
use Yii;
use backend\models\PrfCoupon;
use backend\models\PrfCouponSearch;
use yii\helpers\Url;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
use yii\helpers\VarDumper;

/**
 * CouponController implements the CRUD actions for PrfCoupon model.
 */
class CouponController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all PrfCoupon models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new PrfCouponSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single PrfCoupon model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
    	$couponModel=$this->findModel($id);
          return $this->render('view', [
            'model' => $couponModel
        ]);
    }

    /**
     * Creates a new PrfCoupon model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new PrfCoupon();
        $model->scenario = PrfCoupon::SCENARIO_CREATE;

        if (Yii::$app->request->isPost) {
            if ($model->load(Yii::$app->request->post())) {
            
            	$model->imageFile = UploadedFile::getInstanceByName('PrfCoupon[imageFile]'); 
                $model->start_time=strtotime(Yii::$app->request->post()['PrfCoupon']['start_time']);
                $model->end_time=strtotime(Yii::$app->request->post()['PrfCoupon']['end_time']);
                
                $model->start_time = empty($model->start_time) ? '0' : (strpos($model->start_time, '-') ? intval(strtotime($model->start_time)) : $model->start_time);
                $model->end_time = empty($model->end_time) ? '0' : (strpos($model->end_time, '-') ? intval(strtotime($model->end_time)) + 86399 : $model->end_time);
                $model->last_count = $model->totle_count;
                $userArr = $model->user_types;
                if (!empty($model->user_types) && $model->user_types[0] == 1) {
                    array_splice($userArr, 1, 0, ['2']);
                }
                $model->user_types = $userArr;
                $model->user_types = empty($model->user_types) ? '' : ',' . implode(',', $model->user_types) . ',';
                $model->time_state = empty($model->time_state) ? '0' : intval($model->time_state * 86400);
                if (!empty($model->class3)) {
                    $model->action_id = $model->class3;
                } elseif (!empty($model->class2)) {
                    $model->action_id = $model->class2;
                } elseif (!empty($model->class1)) {
                    $model->action_id = $model->class1;
                }

                //全场优惠券能不能转送
                if ($model->canTrans == 1) {
                    $model->trans_type = '1,2';
                } else {
                    $model->trans_type = '';
                }

                if ($model->validate()) {
                    if ($imgId = $model->upload()) {
                        $model->img_id = $imgId;
                        $model->save(false);
                        return $this->redirect(['view', 'id' => $model->id]);
                    } else {
                        return $this->render('submitSuccess', [
                            'status' => 'warning',
                            'redirectUrl' => Url::to(['coupon/create']),
                            'msg' => "上传失败"
                        ]);
                    }
                } else {
                    return $this->render('create', [
                        'model' => $model,
                    ]);
                }
            } else {
                return $this->render('submitSuccess', [
                    'status' => 'warning',
                    'redirectUrl' => Url::to(['coupon/create']),
                    'msg' => "加载失败"
                ]);
            }
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    public function actionGetClass()
    {
        switch (intval(Yii::$app->request->get('type'))) {
            case 1:
                echo json_encode(['type' => 1, 'result' => GrpClass::class1()], JSON_UNESCAPED_UNICODE);
                break;
            case 2:
                echo json_encode(['type' => 2, 'result' => GrpClass::class2(Yii::$app->request->get('class_id'))], JSON_UNESCAPED_UNICODE);
                break;
            case 3:
                echo json_encode(['type' => 3, 'result' => GrpClass::class3(Yii::$app->request->get('class_id'))], JSON_UNESCAPED_UNICODE);
                break;
            default:
                echo '[]';
        }
    }

    public function actionGetBrand()
    {

        echo json_encode(GrpBrand::find()->select(['name'])->where(['useing' => 1])->indexBy('id')->asArray()->column(), JSON_UNESCAPED_UNICODE);
    }

    /**
     * Updates an existing PrfCoupon model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        //已经使用过优惠券只能更改状态
        if (Yii::$app->request->isPost && $model->totle_count != $model->last_count) {
            $data = Yii::$app->request->post('PrfCoupon', []);
            
           
            $model->state = $data['state'];
            if ($model->save()) {
                return $this->redirect(['view', 'id' => $model->id]);
            } else {
//                print_r($model->errors);return;
                return $this->render('update', [
                    'model' => $model,
                ]);
            }
        }
         
        $model->time_state = empty($model->time_state) ? 0 : $model->time_state / 86400;
        $model->user_types = array_filter(explode(',', $model->user_types));

        if ($model->load(Yii::$app->request->post())) {
        	$model->start_time=strtotime(Yii::$app->request->post()['PrfCoupon']['start_time']);
        	$model->end_time=strtotime(Yii::$app->request->post()['PrfCoupon']['end_time']);
        	
        	$model->start_time = empty($model->start_time) ? '0' : (strpos($model->start_time, '-') ? intval(strtotime($model->start_time)) : $model->start_time);
        	$model->end_time = empty($model->end_time) ? '0' : (strpos($model->end_time, '-') ? intval(strtotime($model->end_time)) + 86399 : $model->end_time);
        	 
            $model->imageFile = UploadedFile::getInstanceByName('PrfCoupon[imageFile]');
            $model->last_count = $model->totle_count;
            $userArr = $model->user_types;
            if (!empty($model->user_types) && $model->user_types[0] == 1) {
                array_splice($userArr, 1, 0, ['2']);
            }
            $model->user_types = $userArr;
            $model->user_types = empty($model->user_types) ? '' : ',' . implode(',', $model->user_types) . ',';
            $model->time_state = empty($model->time_state) ? '0' : $model->time_state * 86400;


            if (!empty($model->class3)) {
                $model->action_id = $model->class3;
            } elseif (!empty($model->class2)) {
                $model->action_id = $model->class2;
            } elseif (!empty($model->class1)) {
                $model->action_id = $model->class1;
            }

            //全场优惠券能不能转送
            if ($model->canTrans == 1) {
                $model->trans_type = '1,2';
            } else {
                $model->trans_type = '';
            }

            if ($model->validate()) {
                if (empty($model->imageFile)) {
                    $model->save(false);
                } else {
                    if ($imgId = $model->upload()) {
                        $model->img_id = $imgId;
                        $model->save(false);
                    } else {
                        return $this->render('submitSuccess', [
                            'status' => 'warning',
                            'redirectUrl' => Url::to(['coupon/create']),
                            'msg' => "上传失败"
                        ]);
                    }
                }
            } else {
                return $this->render('update', [
                    'model' => $model,
                ]);
            }
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
        if($model->start_time==0){
    			$model->start_time= date('Y-m-d H:i:s',time());
    		}else{
    			$model->start_time= date('Y-m-d H:i:s',$model->start_time);
    		}
    		
    		if($model->end_time==0){
    			$model->end_time= date('Y-m-d H:i:s',time());
    		}else{
    			$model->end_time= date('Y-m-d H:i:s',$model->end_time);
    		}
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing PrfCoupon model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the PrfCoupon model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return PrfCoupon the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = PrfCoupon::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
